function getCommands(field, power) {
    let len = Math.sqrt(field.length);
    let rgx = new RegExp(".{1," + len + "}", "g");
    let maze = field.match(rgx).map(s => s.split(''));
    let start = { x: field.indexOf('S') % len, y: Math.floor(field.indexOf('S') / len) };
    let powergrid = maze.map(a => a.map(b => power));
    let queue = [new Node(start.x, start.y, 0, [], 0)]; //o: (0,1,2,3) => (up,right,down,left)

    while (queue[0]) {
        let node = queue.shift();
        if (powergrid[node.y][node.x] < node.power) continue;
        if (maze[node.y][node.x] == 'T') return node.seq;
        else powergrid[node.y][node.x] = node.power;

        let newx = node.x + XfromO(node.o);
        let newy = node.y + YfromO(node.o);
        if (newx >= 0 && newy >= 0 && newx < len && newy < len && maze[newy][newx] != '#') queue.push(new Node(newx, newy, node.o, node.seq.concat(['f']), node.power + 1));
        newx = node.x + XfromO((node.o + 3) % 4);
        newy = node.y + YfromO((node.o + 3) % 4);
        if (newx >= 0 && newy >= 0 && newx < len && newy < len && maze[newy][newx] != '#') queue.push(new Node(newx, newy, (node.o + 3) % 4, node.seq.concat(['r', 'f']), node.power + 2));
        newx = node.x + XfromO((node.o + 1) % 4);
        newy = node.y + YfromO((node.o + 1) % 4);
        if (newx >= 0 && newy >= 0 && newx < len && newy < len && maze[newy][newx] != '#') queue.push(new Node(newx, newy, (node.o + 1) % 4, node.seq.concat(['l', 'f']), node.power + 2));
    }
    return [];
}

function Node(_x, _y, _o, _seq, _power) {
    this.x = _x;
    this.y = _y;
    this.o = _o;
    this.seq = _seq;
    this.power = _power;
    this.toString = function () {
        return ("x: " + this.x + ", y: " + this.y + ", o: " + this.o + ", power: " + this.power + "\nseq: " + this.seq);
    };
}
function XfromO(o) {
    return (o % 2) * (o - 2);
}
function YfromO(o) {
    return ((o + 1) % 2) * (o - 1);
}
console.log(getCommands('S.......T', 6))